package com.rapida.pet.core;

import android.content.Context;
import android.graphics.PixelFormat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;

import com.rapida.framwork.UIViewController;

public abstract class FloatWindow {
	private WindowManager wm;
	private WindowManager.LayoutParams wmParams;
	private float mTouchStartX;
	private float mTouchStartY;
	private float x;
	private float y;

	protected View assistive;
	protected boolean mshow;

	public FloatWindow(Context context) {
		wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

		wmParams = new WindowManager.LayoutParams();
		wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
		wmParams.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
		wmParams.gravity = Gravity.LEFT | Gravity.TOP;
		wmParams.x = 0;
		wmParams.y = 0;
		wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
		wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
		wmParams.format = PixelFormat.RGBA_8888;

		assistive = LayoutInflater.from(context).inflate(R.layout.activity_pet, null);
	}
	
	public void start() {
		if (wm != null) {
			wm.addView(assistive, wmParams);
			setOnTouchListener();
			mshow = true;
		}
	}

	public void remove() {
		if (wm != null) {
			wm.removeView(assistive);
			mshow = false;
		}
	}

	public boolean isShow() {
		return mshow;
	}

	private void setOnTouchListener() {
		assistive.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				x = event.getRawX();
				y = event.getRawY();

				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					mTouchStartX = event.getX();
					mTouchStartY = event.getY() + assistive.getHeight() / 2;
					break;
				case MotionEvent.ACTION_MOVE:
					updateViewPosition();
					break;
				case MotionEvent.ACTION_UP:
					updateViewPosition();
					mTouchStartX = mTouchStartY = 0;
					break;
				}
				return false;
			}

		});
	}

	private void updateViewPosition() {
		wmParams.x = (int) (x - mTouchStartX);
		wmParams.y = (int) (y - mTouchStartY);
		wm.updateViewLayout(assistive, wmParams);
	}
}
